package com.bit.springbook.controller;

import com.bit.springbook.constant.Constant;
import com.bit.springbook.model.Result;
import com.bit.springbook.model.UserInfo;
import com.bit.springbook.service.UserInfoService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserInfoService userInfoService;

    @RequestMapping(value = "/login", produces = "application/json")
    public Result<String> login(String username, String password, HttpSession session) {
        // 校验
        if (!StringUtils.hasLength(username) || !StringUtils.hasLength(password)) {
            return Result.fail("用户名或密码为空");
        }
        // 判断账户是否正确
        UserInfo userInfo = userInfoService.queryUserByName(username);
        if (userInfo == null || userInfo.getId() < 0) {
            return Result.fail("没有该用户");
        }

        if (!userInfo.getPassword().equals(password)) {
            return Result.fail("密码错误");
        }
        // 设置Session
        userInfo.setPassword("");
        session.setAttribute(Constant.USER_SESSION_KEY, userInfo);
        return Result.success("");
    }
}
